﻿using KXmlUIControl.KControl;
using KXmlUIControl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
using LogLib;
using System.IO;
using KeyboardArg;
using ComUIControl;
using KInterfaces;

namespace KWindow.KPageCore
{
    public partial class PageControlBase
    {
        protected TextBox ActivedControl = null;
        protected Label labelTitle = null;
        protected List<Button> BaseButtons = null;
        protected List<Button> Buttons = null;
        protected List<Label> Labels = null;
        protected List<PictureBox> PictureBoxs = null;
        protected List<TextBox> TextBoxs = null;
        protected List<Image> Images = null;
        protected List<Microsoft.Ink.InkPicture> InkPictureBoxs = null;
        protected List<Panel> Panels = null;
        protected List<KCheckBox> CheckBoxs = null;
        protected List<XmlGroupObject> Groups = null;
        protected Dictionary<string, XmlPromptObject> DicPrompts = new Dictionary<string, XmlPromptObject>();
        protected Button buttonNext = null;
        protected Button buttonBack = null;
        protected Button buttonCancel = null;
        protected CountdownControl countdownControl1 = null;
        public int CountdownSecond { get; protected set; } = 0;
        public bool CountdownEnabled { get; private set; }
        protected Dictionary<string, bool> HasInputted = new Dictionary<string, bool>();
        protected Dictionary<string, KeyBoardArgs> TextBoxBindings = null;

        protected string _lastClickTextBox = "";
        protected bool IsMainPage
        {
            get
            {
                if(UIConfig != null)
                {
                    return UIConfig.IsMainForm;
                }
                else
                {
                    return false;
                }
            }
        }

        protected string MyLocation
        {
            get
            {
                if (UIConfig != null)
                {
                    return UIConfig.FormConfig.Location;
                }
                else
                {
                    return "";
                }
            }
        }

        public bool ContainsGroup
        {
            private set;
            get;
        }

        protected TextMapService textMapService = null;

        /// <summary> 
        /// 设计器支持所需的方法: 执行创建自定义控件以及控件布局
        /// </summary>
        protected void InitializeCustomComponent()
        {
            _config = PageConfigService.Instance;
            string directory = GetAssemblyDirectory();
            StaticTypes.SetRootDirectory(directory);
            SetStyles();
            if (UIConfig == null)
            {
                throw new Exception("UIConfig is null.");
            }
            UIConfig.ParentContainer = this;
            ContainsGroup = UIConfig.ContainsGroup;
            Panels = UIConfig.CreatPanels();
            BaseButtons = UIConfig.CreatBaseButtons();
            Buttons = UIConfig.CreatButtons();
            TextBoxs = UIConfig.CreatTextBoxs();
            Labels = UIConfig.CreatLabels();
            PictureBoxs = UIConfig.CreatPictureBoxs();
            InkPictureBoxs = UIConfig.CreatInkPictureBoxs();
            TextBoxBindings = UIConfig.InputtingBindings;
            Images = UIConfig.LoadImages();
            DicPrompts = UIConfig.LoadPrompts();
            countdownControl1 = UIConfig.CreatCountdownControl();
            if (ContainsGroup)
            {
                Groups = UIConfig.Groups;
                CheckBoxs = UIConfig.CreatKCheckBoxs();
            }
            this.SuspendLayout();
            if (TextBoxs != null && TextBoxs.Count > 0)
            {
                textMapService = new TextMapService(TextBoxs, TextBoxBindings);
            }
            foreach (Panel panel in Panels)
            {
                this.Controls.Add(panel);
            }
            foreach (Label lab in Labels)
            {
                this.Controls.Add(lab);
            }
            foreach (TextBox tb in TextBoxs)
            {
                this.Controls.Add(tb);
            }
            foreach (Button btn in BaseButtons)
            {
                this.Controls.Add(btn);
            }
            foreach (Button btn in Buttons)
            {
                this.Controls.Add(btn);
            }
            foreach (PictureBox pic in PictureBoxs)
            {
                this.Controls.Add(pic);
            }
            foreach (Microsoft.Ink.InkPicture pic in InkPictureBoxs)
            {
                this.Controls.Add(pic);
            }

            if (ContainsGroup)
            {
                foreach (KCheckBox cbox in CheckBoxs)
                {
                    this.Controls.Add(cbox);
                }
            }
            //foreach (Control ctl in UIConfig.Controls)
            //{
            //    this.Controls.SetChildIndex(ctl, 0);
            //}
            foreach (PictureBox pic in PictureBoxs)
            {
                ((System.ComponentModel.ISupportInitialize)(pic)).EndInit();
            }

            foreach (Microsoft.Ink.InkPicture pic in InkPictureBoxs)
            {
                ((System.ComponentModel.ISupportInitialize)(pic)).EndInit();
            }

            if (countdownControl1 != null)
            {
                this.Controls.Add(countdownControl1);
                countdownControl1.SetParentName(this.Name);
            }           
            XmlFormObject formConfigs = UIConfig.FormConfig;
            formConfigs.SetValues(this);
            this.ResumeLayout(false);
            this.PerformLayout();
            _voiceEnabled = formConfigs.VoiceEnabled;
            _voiceFileName = formConfigs.VoiceFileName;
            if (UIConfig.CountdownConfig != null)
            {
                CountdownEnabled = UIConfig.CountdownConfig.Enabled;
                CountdownSecond = UIConfig.CountdownConfig.CountDownSecond;
            }
            InitDefaultCtrls();
        }

        /// <summary> 
        /// 设计器支持所需的方法: 执行创建自定义控件以及控件布局
        /// </summary>
        protected void OnRefreshing()
        {
            string directory = GetAssemblyDirectory();
            StaticTypes.SetRootDirectory(directory);
            UIConfig.ParentContainer = this;
            ContainsGroup = UIConfig.ContainsGroup;
            UIConfig.ApplyPanels(Panels);
            UIConfig.ApplyBaseButtons(BaseButtons);
            UIConfig.ApplyButtons(Buttons);
            UIConfig.ApplyLabels(Labels);
            UIConfig.ApplyPictureBoxs(PictureBoxs);
            UIConfig.ApplyInkPictureBoxs(InkPictureBoxs);
            UIConfig.ApplyTextBoxs(TextBoxs);
            if (ContainsGroup)
            {
                UIConfig.ApplyKCheckBoxs(CheckBoxs);
            }
            if(countdownControl1 != null)
            {
                UIConfig.ApplyCountdownControl(countdownControl1);
            }
           
            TextBoxBindings = UIConfig.InputtingBindings;
            Images = UIConfig.LoadImages();
            DicPrompts = UIConfig.LoadPrompts();
            if (textMapService != null)
            {
                textMapService.UpdateData(TextBoxs, TextBoxBindings);
            }

            XmlFormObject formConfigs = UIConfig.FormConfig;
            formConfigs.SetValues(this);
            if(UIConfig.CountdownConfig != null)
            {
                CountdownEnabled = UIConfig.CountdownConfig.Enabled;
                CountdownSecond = UIConfig.CountdownConfig.CountDownSecond;
            }
            InitDefaultCtrls();
        }

        /// <summary>
        /// 初始化窗体个性化控件(创建后只调用一次)
        /// </summary>
        public virtual void InitCtrls()
        {
            if(Initialized)
            {
                return;
            }
            if(this.InvokeRequired)
            {
                Action handler = new Action(InitCtrls);
                this.Invoke(handler);
                return;
            }
            string appName = GetAppName();
            Log.WriteAsync($"====================[{appName} init start]====================");
            InitializeCustomComponent();
            Log.WriteAsync($"====================[{appName} init end]====================");
            Initialized = true;
        }

        /// <summary>
        /// 初始化默认的控件
        /// </summary>
        protected void InitDefaultCtrls()
        {
            Control c0 = GetControl<Button>("buttonCancel");
            if (c0 != null)
            {
                buttonCancel = c0 as Button;
                SetButtonDefaultStyles(buttonCancel);
            }
            Control c1 = GetControl<Button>("buttonNext");
            if (c1 != null)
            {
                buttonNext = c1 as Button;
                SetButtonDefaultStyles(buttonNext);
            }
            Control c2 = GetControl<Button>("buttonBack");
            if (c2 != null)
            {
                buttonBack = c2 as Button;
                SetButtonDefaultStyles(buttonBack);
            }
            Control c3 = GetControl<Label>("labelTitle");
            if (c3 != null)
            {
                labelTitle = c3 as Label;
            }
            if(countdownControl1 != null)
            {
                countdownControl1.Visible = CountdownEnabled;
            }
            
            if (ContainsGroup)
            {
                try
                {
                    InitGroupCtrls();
                    ShowRootGroupCtrls();
                    foreach (KCheckBox cbox in CheckBoxs)
                    {
                        cbox.CheckedChanged += CheckBox_CheckedChanged;
                    }
                }
                catch (Exception ex)
                {
                    string errInfo = "InitGroupCtrls发生了异常: \n";
                    MsgBox.Show(errInfo + ex.Message);
                    Log.WriteException(ex.ToString());
                }
            }
        }

        protected Image GetImage(string name)
        {
            return Images.Find(r => ((string)(r.Tag)).Equals(name));
        }

        protected Control GetControl<Tc>(string name)
        {
            Type type = typeof(Tc);
            foreach (Control ctl in Controls)
            {
                if (ctl.GetType() == type)
                {
                    if (ctl.Name.Equals(name))
                    {
                        return ctl;
                    }
                }
            }
            return null;
        }

        protected void LoadImages()
        {

        }

        public void SetStyles()
        {
            this.DoubleBuffered = true;//设置本窗体
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲
        }

        public void SetButtonDefaultStyles(Button btn)
        {
            if (btn == null)
            {
                Log.WriteAsync("控件实例为空");
                return;
            }
            btn.BackColor = Color.Transparent;
            btn.FlatStyle = FlatStyle.Flat;
            btn.FlatAppearance.BorderSize = 0;
            btn.FlatAppearance.MouseDownBackColor = Color.Transparent;
            btn.FlatAppearance.MouseOverBackColor = Color.Transparent;
            btn.FlatAppearance.BorderSize = 0;
        }

        //委托更新控件
        public void UpdatePictureBox(PictureBox pbx, string imgPath)
        {
            try
            {
                pbx.BeginInvoke(new Action(() =>
                {
                    //if (File.Exists(imgPath))
                    //{
                    //    FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
                    //    pbx.Image = Image.FromStream(fs);
                    //    fs.Close();
                    //}

                    if (File.Exists(imgPath))  //这样才可以加载gif
                    {
                        Image img = Image.FromFile(imgPath);
                        pbx.Image = img;
                    }
                }));
            }
            catch (Exception ex)
            {
            }
        }

        public void UpdatePictureBox(PictureBox pbx, Image img)
        {
            pbx.BeginInvoke(new Action(() =>
            {

                pbx.Image = img;

            }));
        }

        public void SetPictureBoxVisible(PictureBox pbx, bool isShow)
        {
            pbx.BeginInvoke(new Action(() =>
            {
                pbx.Visible = isShow;
            }));
        }

        /// <summary>
        /// 应用语言
        /// </summary>
        /// <param name="code"></param>
        public virtual void ApplyLanguage(string code)
        {
            LanguageCode = code;
            OnRefreshing();
        }
    }
}
